const baseAuth = require('basic-auth')
const jwt = require('jsonwebtoken')
class Auth {
  constructor (level) {
    this.level = level || 1
    // 权限的分级
    Auth.USER = 8
    Auth.ADMIN = 16
    Auth.SUPER_ADMIN = 32
  }

  get m () {
    return async (ctx, next) => {
      let errMsg = 'token不合法'
      const token = baseAuth(ctx.req)
      if(!token || !token.name) {
        throw new global.errs.Forbbiden(errMsg)
      }
      try {
        var decode = jwt.verify(token.name, global.config.security.secretKey)
      } catch (error) {
        //token 不合法 || token 过期
        if(error.name === 'TokenExpiredError') {
          errMsg = 'token过期'
        }
        throw new global.errs.Forbbiden(errMsg)
      }

      if(decode.scope < this.level) {
        throw new global.errs.Forbbiden('权限不足')
      }

      ctx.auth = {
        uid: decode.uid,
        scope: decode.scope
      }

      await next()
      // token 检测
      // http 规定的 身份验证机制 HttpBaseAuth 使用header进行传递
      // httpBaseAuth 会对传递的 令牌 进行base64 加密 
      
      // 测试token：eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIsInNjb3BlIjoyLCJpYXQiOjE1Njc0NzcyNDQsImV4cCI6MTU3MDA2OTI0NH0.trl_bT91n3u-Xzqe0SRaKwtvB5ORG4ha6tKb9hgk3aQ
    }
  }

  static async verifyToken (token) {
    try {
      jwt.verify(token, global.config.security.secretKey)
      return true
    } catch (error) {
      return false
    }
  }
}

module.exports = {
  Auth
}